package com.phpxiu.app.view.dialog;

import android.content.Context;
import android.content.Intent;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.ImageView;

import com.phpxiu.app.config.Constants;
import com.phpxiu.app.config.HttpConfig;
import com.phpxiu.app.kkylive.KKYApp;
import com.phpxiu.app.kkylive.R;
import com.phpxiu.app.model.CurLiveInfo;
import com.phpxiu.app.model.LiveRoomInfo;
import com.phpxiu.app.model.MySelfInfo;
import com.phpxiu.app.model.MsgSender;
import com.phpxiu.app.model.event.OnBackCamera;
import com.phpxiu.app.model.event.OnChatRoomReply;
import com.phpxiu.app.model.event.OnRefreshFollowCount;
import com.phpxiu.app.model.event.SendMsgFailEvent;
import com.phpxiu.app.model.msg.CommonMsg;
import com.phpxiu.app.model.msg.ManageMsg;
import com.phpxiu.app.model.response.MsgModel;
import com.phpxiu.app.model.response.RoomCardModel;
import com.phpxiu.app.okhttp.OKHttp;
import com.phpxiu.app.okhttp.OKHttpResponseModel;
import com.phpxiu.app.okhttp.handler.OKHttpUIHandler;
import com.phpxiu.app.okhttp.param.OKHttpParam;
import com.phpxiu.app.utils.KKYUtil;
import com.phpxiu.app.view.RoomVideoRoom;
import com.phpxiu.app.view.RoomFansRank;
import com.phpxiu.app.view.custom.FlyWordsSwitchView;
import com.tencent.TIMMessage;
import com.tencent.TIMTextElem;
import com.tencent.TIMValueCallBack;

import de.greenrobot.event.EventBus;
import de.greenrobot.event.Subscribe;

/**
 * Created by 吴金洲 on 2016/6/25
 */
public class LiveRoomWin extends LiveRoomAnimWin implements FlyWordsSwitchView.FlyWordsSwitchListener,TextWatcher {
    private final static String TAG="LiveRoomWin";
    private CommonMsg commonMsg;
    private RoomUserCard card;//卡片
    private OKHttpParam cardParam;
    private boolean isRequestingCard=false;//正在请求卡片信息
    private long muteExpireAt=-1;//禁言到期时间
    private RoomShareMenus shareOptionBoard;//分享平台面板
    private FlyWordsSwitchView flyWordsSwitch_;
    private ImageView flyWordsSwitch;
    private boolean isFlyWordMsg=false;
    private String flyHint,commonHint;
    public LiveRoomWin(RoomVideoRoom context,LiveRoomInfo roomInfo) {
        super(context,roomInfo);
        commonMsg=new CommonMsg();
    }

    @Override
    protected void init() {
        super.init();
        flyHint=getContext().getString(R.string.room_bullet_msg_hint);
        commonHint=getContext().getString(R.string.room_group_msg_hint);
        flyWordsSwitch=(ImageView)findViewById(R.id.fly_words_switch_btn);
        flyWordsSwitch.setOnClickListener(this);
        //flyWordsSwitch.addFlyWordsSwitchListener(this);
        mInput.addTextChangedListener(this);
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()){
            case R.id.fly_words_switch_btn:
                //flyWordsSwitch.switchState();
                flyWordsSwitch.setSelected(!flyWordsSwitch.isSelected());
                if(flyWordsSwitch.isSelected()){
                    flyWordsSwitch.setImageResource(R.mipmap.fly_words_switch_on);
                    isFlyWordMsg=true;
                    mInput.setHint(flyHint);
                }else{
                    flyWordsSwitch.setImageResource(R.mipmap.fly_words_switch_off);
                    isFlyWordMsg=false;
                    mInput.setHint(commonHint);
                }
                break;
        }
    }

    @Override
    public void show() {
        sp=getContext().getSharedPreferences(MUTE_STATE, Context.MODE_PRIVATE);
        super.show();
    }

    @Override
    public void handleMsg(Message msg) {
        super.handleMsg(msg);
        switch (msg.what){
            case HANDLE_REPLY_MSG://回复消息
                String nick="@"+msg.obj.toString()+" ";
                mInput.setText(nick);
                mInput.setSelection(nick.length());
                openInputBtn.performClick();
                break;
            case HANDLE_HIDE_ATTENTION:
                attentionBtnHideAnim.start();
                break;
            case HANDLE_FLASHLIGHT_STATE_REFRESH:
                flashlightOff=true;
                flashlightSwitch.setImageResource(R.mipmap.flashlight_option_on_icon);
                break;
            default:
                break;
        }
    }


    /**
     * 显示用户信息窗口
     */
    @Override
    public void onShowUserWindow(final String uid) {
        if(isRequestingCard){
            mainView.showTopMsg(getContext().getString(R.string.ui_room_card_disable));
            return;
        }
        if(cardParam==null){
            cardParam=OKHttpParam.builder();
        }
        cardParam.clear();
        String url=null;
        if(uid.equals(CurLiveInfo.getHostID())){
            url= HttpConfig.API_GET_ROOM_HOST_CARD;
            cardParam.put("uid", CurLiveInfo.getHostID());
        }else{
            url= HttpConfig.API_GET_ROOM_USER_CARD;
            cardParam.put("uid",uid);
            cardParam.put("host_id", CurLiveInfo.getHostID());
        }
        isRequestingCard=true;
        OKHttp.post(url, cardParam.jsonParam(), TAG, new OKHttpUIHandler(RoomCardModel.class) {
            @Override
            public void onSuccess(Object model) {
                RoomCardModel m = (RoomCardModel) model;
                KKYUtil.log("房间卡片信息获取结果：" + m.getResponseStr());
                if (card == null) {
                    card = new RoomUserCard(getContext());
                    card.getWindow().getAttributes().width=(int)KKYApp.screenWidth;
                }
                card.setParent(LiveRoomWin.this);
                card.show(m.getData());
                isRequestingCard=false;
            }

            @Override
            public void onErr(String errMsg) {
                isRequestingCard=false;
                mainView.showTopMsg(errMsg);
            }
        });
    }

    /**
     * 广播管理员变更系统消息
     */
    public void broadcastAdmin(MsgSender tUser,boolean cancelAdmin){
        MsgModel msgModel=new MsgModel();
        msgModel.setUserAction(cancelAdmin==true? Constants.AV_IM_CMD_NOTICE_CANCEL_ADMIN:Constants.AV_IM_CMD_NOTICE_ADD_ADMIN);
        ManageMsg msg=new ManageMsg();
        msg.setTuser(tUser);
        msgModel.setActionParam(gson.toJson(msg));
        roomPresenter.sendGroupNoticeMessage(gson.toJson(msgModel), new TIMValueCallBack<TIMMessage>() {
            @Override
            public void onError(int i, String s) {
            }

            @Override
            public void onSuccess(TIMMessage timMessage) {
                if (timMessage.getElement(0) == null) {
                    return;
                }
                onReceiveCustomMsg(timMessage, timMessage.getElement(0));
            }
        });
    }

    /**
     * 广播禁言系统消息
     */
    public void broadcastMute(MsgSender tUser){
        MsgModel msgModel=new MsgModel();
        msgModel.setUserAction(Constants.AV_IM_CMD_NOTICE_MUTE);
        ManageMsg msg=new ManageMsg();
        msg.setTuser(tUser);
        msgModel.setActionParam(gson.toJson(msg));
        roomPresenter.sendGroupNoticeMessage(gson.toJson(msgModel), new TIMValueCallBack<TIMMessage>() {
            @Override
            public void onError(int i, String s) {

            }

            @Override
            public void onSuccess(TIMMessage timMessage) {
                if (timMessage.getElement(0) == null) {
                    return;
                }
                onReceiveCustomMsg(timMessage, timMessage.getElement(0));
            }
        });
    }

    /**
     * 广播关注主播消息
     */
    public void broadcastAttention(){
        if(mMsgSender ==null){
            mMsgSender =new MsgSender();
            mMsgSender.setUid(MySelfInfo.getInstance().getId());
            mMsgSender.setNickname(MySelfInfo.getInstance().getNickName());
            mMsgSender.setAvatar(MySelfInfo.getInstance().getAvatar());
            mMsgSender.setLvl(MySelfInfo.getInstance().getLvl());
        }
        MsgModel msgModel=new MsgModel();
        msgModel.setUserAction(Constants.AV_IM_CMD_NOTICE_ATTENTION);
        ManageMsg msg=new ManageMsg();
        msg.setFuser(mMsgSender);
        msgModel.setActionParam(gson.toJson(msg));
        roomPresenter.sendGroupNoticeMessage(gson.toJson(msgModel), new TIMValueCallBack<TIMMessage>() {
            @Override
            public void onError(int i, String s) {

            }

            @Override
            public void onSuccess(TIMMessage timMessage) {
                if (timMessage.getElement(0) == null) {
                    return;
                }
                onReceiveCustomMsg(timMessage, timMessage.getElement(0));
            }
        });
    }

    /**
     * 关注主播
     */
    @Override
    protected void attentionUser(){
        OKHttpParam attParam=OKHttpParam.builder();
        attParam.put("uid",CurLiveInfo.getHostID());
        OKHttp.post(HttpConfig.API_ATTENTION_USER,attParam.jsonParam(),TAG,new OKHttpUIHandler(OKHttpResponseModel.class) {
            @Override
            public void onSuccess(Object model) {
                mainView.showTopMsg(getContext().getString(R.string.room_follow_success));
                EventBus.getDefault().post(new OnRefreshFollowCount(true));//更新我的关注数量
                broadcastAttention();
                handler.sendEmptyMessage(HANDLE_HIDE_ATTENTION);
            }

            @Override
            public void onErr(String errMsg) {
                mainView.showTopMsg(errMsg);
            }
        });
    }

    /**
     * 回复某人
     */
    @Subscribe
    public void onReplySomeBody(OnChatRoomReply event){
        Message msg=handler.obtainMessage();
        msg.what=HANDLE_REPLY_MSG;
        msg.obj=event.getNick();
        handler.sendMessage(msg);
    }

    /**
     * 摄像头变换事件
     * @param event
     */
    @Subscribe
    public void onCameraSwitch(OnBackCamera event){
        isCanSwitchLight=!event.isFront();
        roomPresenter.flashLightStatusOff();
        if(isCanSwitchLight){
           KKYUtil.log("当前为后置摄像头");
        }else{
            KKYUtil.log("当前为前置摄像头");
        }
        handler.sendEmptyMessage(HANDLE_FLASHLIGHT_STATE_REFRESH);
    }

    @Override
    protected void goRank() {
        if(MySelfInfo.getInstance().getIdStatus()!=Constants.HOST) {
            Intent roomRank = new Intent(getContext(), RoomFansRank.class);
            roomRank.putExtra(RoomFansRank.EXTRA_PARAM_USER_ID_KEY, CurLiveInfo.getHostID());
            roomRank.putExtra(RoomFansRank.EXTRA_PARAM_USER_TICKETS_KEY, currentGain + "");
            getContext().startActivity(roomRank);
        }
    }

    @Override
    protected void openShareMenus() {
        super.openShareMenus();
        if(shareOptionBoard==null){
            shareOptionBoard=new RoomShareMenus(getContext());
            shareOptionBoard.getWindow().getAttributes().width=(int)KKYApp.screenWidth;
        }
        shareOptionBoard.show(mRoom);
    }


    @Override
    public void FlyWordsSwitchOn() {
        isFlyWordMsg=true;
        mInput.setHint(flyHint);
    }

    @Override
    public void FlyWordsSwitchOff() {
        isFlyWordMsg=false;
        mInput.setHint(commonHint);
    }

    /**
     * 发送聊天消息
     */
    @Override
    protected void onSendCommonMsg(String msg) {
        hideSoftInput(mInput);
        muteExpireAt=sp.getLong(MUTE_EXPIRE_AT+CurLiveInfo.getHostID(),-1);
        if(muteExpireAt<System.currentTimeMillis()){//已过禁言时间
            if(muteExpireAt!=-1) {//有记录则删除记录
                sp.edit().remove(MUTE_EXPIRE_AT + CurLiveInfo.getHostID()).commit();
            }
            if(TextUtils.isEmpty(msg)){
                return;
            }
            if(mMsgSender ==null){
                mMsgSender =new MsgSender();
                mMsgSender.setUid(MySelfInfo.getInstance().getId());
                mMsgSender.setAvatar(MySelfInfo.getInstance().getAvatar());
                mMsgSender.setNickname(MySelfInfo.getInstance().getNickName());
                mMsgSender.setLvl(MySelfInfo.getInstance().getLvl());
            }
            if(isFlyWordMsg){//当前发送模式为弹幕，创建弹幕，请求验证发送
                CommonMsg word=new CommonMsg();
                word.setType("1");
                word.setFuser(mMsgSender);
                word.setMsg(msg);
                requestSendFlyWord(word);
                return;
            }
            commonMsg.setFuser(mMsgSender);
            commonMsg.setType("0");
            commonMsg.setMsg(msg);
            TIMMessage timMessage = new TIMMessage();
            TIMTextElem elem = new TIMTextElem();
            elem.setText(gson.toJson(commonMsg));
            if (timMessage.addElement(elem) != 0) {
                return;
            }
            roomPresenter.sendGroupText(timMessage);
        }else{
            mainView.showTopMsg(getContext().getString(R.string.room_mute_msg));
        }
        mInput.setText("");
    }

    /**
     * 请求发送弹幕词
     */
    public void requestSendFlyWord(final CommonMsg word){
        OKHttpParam param=OKHttpParam.builder(false);
        param.put("liveid",roomInfo.getLiveid());
        mInput.setText("");
        OKHttp.post(HttpConfig.API_SEND_FLY_WORD,param.jsonParam(),TAG,new OKHttpUIHandler(OKHttpResponseModel.class) {
            @Override
            public void onSuccess(Object model) {
                OKHttpResponseModel m=(OKHttpResponseModel)model;
                KKYUtil.log("发送弹幕结果："+m.getResponseStr());
                broadCastFlyWords(word);
            }

            @Override
            public void onErr(String errMsg) {
                if(mainView!=null){
                    mainView.showTopMsg(errMsg);
                }
            }
        });
    }

    /**
     * 广播飞弹幕
     * @param word
     */
    private void broadCastFlyWords(CommonMsg word){
        TIMMessage timMessage = new TIMMessage();
        TIMTextElem elem = new TIMTextElem();
        elem.setText(gson.toJson(word));
        if (timMessage.addElement(elem) != 0) {
            return;
        }
        roomPresenter.sendGroupText(timMessage);
    }

    /**
     * 打开私信面板
     */
    @Override
    protected void openMsgBoard() {
        super.openMsgBoard();
        if(mRoom!=null){
            mRoom.showC2CListWin();
        }
    }

    /**
     * 发送消息失败提示
     */
    @Subscribe
    public void onSendMsgFail(SendMsgFailEvent failEvent){
        if(mainView!=null){
            mainView.showTopMsg(failEvent.getErr());
        }
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        if(TextUtils.isEmpty(s)){
            sendMsgBtn.setEnabled(false);
        }else{
            if(!sendMsgBtn.isEnabled()){
                sendMsgBtn.setEnabled(true);
            }
        }
    }

    @Override
    public void afterTextChanged(Editable s) {

    }

    @Override
    public void dismiss() {
        handler.removeCallbacksAndMessages(null);
        super.dismiss();
        framesAnimView=null;
    }
}
